﻿open System

let host_path = "C:\WINDOWS\System32\drivers\etc\hosts"

let read_hosts_file _ = 
    System.IO.File.ReadAllLines host_path

let write_host_file hosts_list = 
    System.IO.File.WriteAllLines (host_path, hosts_list, Text.Encoding.UTF8)
    printfn "%A" hosts_list
    
let rec change_ip_addr (url_list: string list) ip_addr (map: Map<string ,string>)  : Map<string ,string> = 
    match url_list with
    | [] -> map
    | head::tail -> change_ip_addr tail ip_addr (map.Add (head, ip_addr)) 
        
    
let change_pigx_host ip_addr = 
    let pigx_urls = [
        "pigx-register"
        "pigx-mysql"
        "pigx-redis"
        "pigx-sentinel"
        "pigx-auth"
        "pigx-config"
        "pig-redis"
        "pigx-gateway"         
    ]
    
    read_hosts_file ()
    |> Array.filter (fun str -> not (String.IsNullOrEmpty(str)))
    |> Array.map (fun str -> str.Split " ")
    |> Array.map (fun arr -> (arr.[1], arr.[0]))
    |> Map.ofArray
    |> change_ip_addr pigx_urls ip_addr
    |> Map.toArray
    |> Array.map (fun (url, ip) -> $"{ip} {url}")
    |> write_host_file

    


[<EntryPoint>]
let main argv = 
    
    match argv.Length with
    | 1 -> change_pigx_host argv.[0]
    | _ -> printfn $"参数个数错误，应该为 1，实际为 {argv.Length}。"
    
    0
